package com.eco.fanliapp.job.footprintjob;

import com.eco.fanliapp.entity.AppUserSearchHistory;
import com.eco.fanliapp.service.IAppUserSearchHistoryService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.Serializable;
import java.util.*;
import java.util.Calendar;

/**
 * @date 2020-01-16
 */
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
@Slf4j
public class SearchHistoryTask implements Job, Serializable {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IAppUserSearchHistoryService iAppUserSearchHistoryService;

    public SearchHistoryTask(){}

    @Override
    public void execute(JobExecutionContext context) {

        //取得job详情
        JobDetail jobDetail = context.getJobDetail();

        JobDataMap dataMap = jobDetail.getJobDataMap();

        int executeCount = 0;
        if (dataMap.containsKey("runCount")) {
            executeCount = dataMap.getInt("runCount");
        }

        // 增量计数并将其存储回 JobDataMap，这样可以适当保持工作状态
        executeCount++;
        dataMap.put("runCount", executeCount);

        long startTime = System.currentTimeMillis();
        log.info("***************************************开始执行搜索记录定时任务：executeCount=" + executeCount + "--startTime=" + startTime);

        //1从缓存取出搜索记录
        java.util.Calendar cale = java.util.Calendar.getInstance();
        int hour = cale.get(Calendar.HOUR_OF_DAY);
        if(hour == 0){
            hour = 23;
        }else {
            hour--;
        }

        //先从缓存中搜索记录
        String redisKeyStr = "AppUserSearchHistory_" + hour;//当前小时
        List<AppUserSearchHistory> searchHistoryList = new ArrayList<>();
        if (redisTemplate.hasKey(redisKeyStr)) {
            Map<String, Set<String>> searchMap = (Map)redisTemplate.opsForValue().get(redisKeyStr);
            for (Map.Entry<String, Set<String>> entry : searchMap.entrySet()) {
                String userId = entry.getKey();
                Set<String> itemIdSet = entry.getValue();
                Iterator<String> it = itemIdSet.iterator();
                while (it.hasNext()) {
                    String itemId = it.next();
                   //添加搜索记录对象
                    AppUserSearchHistory appUserSearchHistory = new AppUserSearchHistory();
                    appUserSearchHistory.setItemId(Long.valueOf(itemId));
                    appUserSearchHistory.setUserId(Long.valueOf(userId));
                    appUserSearchHistory.setSearchCount(1);
                    searchHistoryList.add(appUserSearchHistory);
                }

            }
        }
        if(searchHistoryList != null && searchHistoryList.size() > 0){
            iAppUserSearchHistoryService.saveBatch(searchHistoryList);
        }
        long endTime = System.currentTimeMillis();
        log.info("***************************************结束执行搜索记录定时任务：executeCount=" + executeCount + "--endTime=" + endTime + "--耗时=" + (endTime - startTime));
    }

    public static void main(String[] args) {
        java.util.Calendar cale = java.util.Calendar.getInstance();
        cale.set(Calendar.HOUR_OF_DAY, 1);
        cale.set(Calendar.MINUTE, 59);
        int hour = cale.get(Calendar.HOUR_OF_DAY);
        if(hour == 0){
            hour = 23;
        }else {
            hour--;
        }
        log.info(hour+"小时");
    }
}
